package com.csii.adhoc.controller.info;

import com.csii.adhoc.annotation.OperationLog;
import com.csii.adhoc.exception.ParamValidityException;
import com.csii.adhoc.system.auth.AuthVo;
import com.csii.adhoc.system.auth.service.AuthService;
import com.csii.adhoc.util.DateUtils;
import com.csii.adhoc.util.ParamCheckUtils;
import com.csii.adhoc.util.StringUtils;
import com.csii.result.APIResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 权限控制层
 * @author: panChuanJiang
 * @create: 2021-01-28 16:08
 */
@Slf4j
@RestController
@RequestMapping("authority")
public class AuthController {
    @Resource
    private AuthService authService;

    @RequestMapping("authorityMaintain")
    @OperationLog("权限维护")
    public APIResult<?> authorityMaintain(@RequestBody AuthVo authVo) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        String userId = Optional.ofNullable(String.valueOf(SecurityUtils.getSubject().getPrincipal())).orElse("未知用户");
        authVo.setUpdatedBy(userId)
                .setUpdatedDt(DateUtils.getDateString("yyyyMMddHHmmss"));
        authService.authMaintain(authVo, authVo.getOptMode());
        return APIResult.successResult(null);
    }

    /**
     * @param authVo authVo
     */
    @RequestMapping("authorityQuery")
    public APIResult<?> authorityQuery(@RequestBody AuthVo authVo) {
        return APIResult.successResult(authService.selectListAuth(authVo));
    }

    /**
     * 根据角色查询权限
     * @param params 角色
     */
    @RequestMapping("getRoleAuthority")
    public APIResult<?> getRoleAuthority(@RequestBody Map<String,String> params) {
        String roleId =  params.get("roleId");
        String type = params.get("type");
        return APIResult.successResult(authService.getRoleAuthority(roleId,type));
    }

    /**
     * 根据用户id和目录type查询权限
     * @param params userId type
     */
    @RequestMapping("getUserAuthority")
    public APIResult<?> getUserAuthority(@RequestBody Map<String, String> params) {
        String name = params.get("name");
        if (StringUtils.isEmpty(name)){
            name = String.valueOf(SecurityUtils.getSubject().getPrincipal());
        }
        String type = params.get("type");
        if (ParamCheckUtils.checkStringEmpty(name, type)) {
            throw new ParamValidityException(String.format("参数为空,name:%s,type:%s", name,type));
        }
        return APIResult.successResult(authService.getUserAuthority(name,type));
    }
}
